package com.yx.cloud.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.iot.base.bean.account.Account;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.activity.AboutUsActivity;
import com.yx.cloud.activity.AccountManagActivity;
import com.yx.cloud.activity.HelpAndFeedbackActivity;
import com.yx.cloud.activity.SwitchLanguageActivity;
import com.yx.cloud.bean.AppUpdateBean;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.product.laser.inxni.INXNIConstant;
import com.yx.cloud.utils.AppUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RomUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import de.hdodenhof.circleimageview.CircleImageView;


public class UserInfoFragment extends Fragment implements View.OnClickListener {
    private View view;
    private RelativeLayout rlAboutUs, rlHelpAndFeedback, rlMall, rlSwitchLanguage;
    private Account account;
    private String username, nickName, phone, email;
    private int regFrom;
    private TextView tvLiftNickName, tvLiftAccount;
    private CircleImageView headPortrait;
    private Dialog dialog;
    private ImageView ivSetting;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        view = inflater.inflate(R.layout.user_info_fragment_item, null);
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        rlAboutUs = view.findViewById(R.id.rl_aboutUs);
        rlHelpAndFeedback = view.findViewById(R.id.rl_helpAndFeedback);
        rlMall = view.findViewById(R.id.rl_mall);
        rlSwitchLanguage = view.findViewById(R.id.rl_switchLanguage);
        tvLiftNickName = view.findViewById(R.id.tv_liftNickName);
        headPortrait = view.findViewById(R.id.headPortrait);
        tvLiftAccount = view.findViewById(R.id.tv_liftAccount);
        ivSetting = view.findViewById(R.id.iv_setting);
    }

    private void initData() {
        AppContext.getAccountService().getUserInfo();
        rlAboutUs.setOnClickListener(this);
        rlSwitchLanguage.setOnClickListener(this);
        rlMall.setOnClickListener(this);
        rlHelpAndFeedback.setOnClickListener(this);
        ivSetting.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.rl_aboutUs) {
            //关于
            Intent_utils.enterIntentMenu(getActivity(), AboutUsActivity.class);
            //取消主界面注册,避免多次注册
        } else if (id == R.id.rl_helpAndFeedback) {
            //帮助与反馈
            Intent_utils.enterIntentMenu(getActivity(), HelpAndFeedbackActivity.class);
        } else if (id == R.id.iv_setting) {
            Intent intent = new Intent(getActivity(), AccountManagActivity.class);
            intent.putExtra("username", username);
            intent.putExtra("nickName", Constants.nickName);
            startActivity(intent);
        } else if (id == R.id.rl_switchLanguage) {
            //语言设置
            Intent_utils.enterIntentMenu(getActivity(), SwitchLanguageActivity.class);
        } else if (id == R.id.rl_mall) {
            //商城
            boolean taobaoPk = AppUtil.isPkgInstalled(getActivity(), "com.taobao.taobao");//淘宝
            boolean tmallPk = AppUtil.isPkgInstalled(getActivity(), "com.tmall.wireless");//天猫
            if (taobaoPk && tmallPk) {
                Intent_utils.gotoShop(getActivity(), "tmall://page.tm/shop?shopId=468067551");
            } else if (tmallPk) {
                Intent_utils.gotoShop(getActivity(), "tmall://page.tm/shop?shopId=468067551");
            } else if (taobaoPk) {
                Intent_utils.gotoShop(getActivity(), "taobao://shop.m.taobao.com/shop/shop_index.htm?shop_id=468067551");
            } else {
                Intent_utils.gotoShop(getActivity(), "https://inxni.m.tmall.com");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_ACCOUNT_INFO:
                // 用户信息
                if (event.isResult()) {
                    Account data = (Account) event.getContent();
                    account = data;
                    AppContext.get().setAccount(account);
                    String nickname = data.getNickname();
                    String userAccount = data.getAccount();
                    if ("".equals(nickname)) {
                        Constants.nickName = userAccount;
                    } else {
                        Constants.nickName = nickname;
                    }
                    INXNIConstant.USER_ID = userAccount;
                    tvLiftNickName.setText(Constants.nickName);
                    tvLiftAccount.setText(userAccount);
                    LogUtils.i("从服务器上加载头像 " + data.getHeadPicUrl());
                    //从服务器上加载头像
                    AppContext.getAccountService().getUserProfile(data.getHeadPicUrl());
                }

                break;
            case Event.MESSAGE_TYPE_REQUEST_APP_UPDATE:
                // APP 新版本
                AppUpdateBean appUpdateBean = (AppUpdateBean) event.getContent();
                String mContent = getString(R.string.MY_Version_New_Tip).replace("{X}", appUpdateBean.getVersion());
                //对话框
                newAPPVersionsHintDialog(getActivity(), mContent, getString(R.string.MY_Version_New), getString(R.string.U_NoUpdate), getString(R.string.U_Update), appUpdateBean.getDownLoadUrl());
                break;
            case Event.MESSAGE_TYPE_DOWNLOAD_HEADPICTRUE:
                //头像
                if (event.isResult()) {
                    LogUtils.i("  头像* **************  ");
                    Bitmap bitmap = (Bitmap) event.getContent();
                    if (bitmap != null) {
                        account.setHeadPic(bitmap);
                        headPortrait.setImageBitmap(bitmap);
                    }
                }
                break;
        }
    }

    private void detectNewVersions() {
        //从官网获取版本号比对更新
       /* OkhttpUtil.get("https://www.inxni.com/appvision/android", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    if (jsonObject.has("data")) {
                        String updateStr = jsonObject.getString("data");
                        LogUtils.i("data is " + json);
                        JSONObject updateObject = new JSONObject(updateStr);
                        if (updateObject.has("version")) {
                            String newVersion = updateObject.getString("version");
                            String currentVersion = AppUtil.getVersionName(getActivity());
                            int result = AppUtil.compareVersion(newVersion, currentVersion);
                            LogUtils.i("compare result is " + result);
                            if (AppUtil.compareVersion(newVersion, currentVersion) == 1) {
                                String forceUpdate = updateObject.getString("forceUpgrade");
                                LogUtils.i("forceUpgrade is " + forceUpdate);
                                if (forceUpdate.equals("yes")) {
                                    AppUpdateBean appUpdateBean = new AppUpdateBean();
                                    appUpdateBean.setVersion(newVersion);
                                    appUpdateBean.setDownLoadUrl(updateObject.getString("downloadUrl"));
                                    LogUtils.i("dow Url is " + appUpdateBean.getDownLoadUrl());
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_REQUEST_APP_UPDATE).content(appUpdateBean).send();
                                }
                                SharedPrefsUtil.putValue(getActivity(), Constants.NOT_READ_TAG, Constants.KEY_APP_HAS_UPPER_VERSION, true);
                                Event.newBuilder().type(Event.MESSAGE_TYPE_REQUEST_APP_UPDATE_ABOUT).result(true).send();
                            } else {
                                SharedPrefsUtil.putValue(getActivity(), Constants.NOT_READ_TAG, Constants.KEY_APP_HAS_UPPER_VERSION, false);
                                Event.newBuilder().type(Event.MESSAGE_TYPE_REQUEST_APP_UPDATE_ABOUT).result(false).send();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });*/
    }

    /**
     * 新版本Dialog
     */
    public void newAPPVersionsHintDialog(Context context, String content, String
            dialogTitle, String str1, String str2, String url) {
        if (dialog == null) {
            dialog = new Dialog(context);
        }
        if (dialog.isShowing()) {
            return;
        }
        dialog.setContentView(R.layout.outlogin_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_outLoginCancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogTitle);
        TextView mContent = dialog.findViewById(R.id.tv_content);

        mTvDialogTitle.setText(dialogTitle);
        mContent.setText(content);

        mBtnOutLoginCancel.setText(str1);
        mBtnOutLoginConfirm.setText(str2);
        mBtnOutLoginConfirm.setTextColor(ContextCompat.getColor(getActivity(), R.color.button_color2));

        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
//                Log.i(TAG, "helpServiceTelHintDialog ------");
                //从其他浏览器打开
                Intent_utils.gotoShop(getActivity(), url);
                dialog.dismiss();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }
}
